#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量处理 Markdown 文件中的图片表格并生成拼接图片
使用方法：python merge-images-batch.py <markdown文件路径>
"""

import re
import os
import sys
from pathlib import Path
from PIL import Image


def extract_image_paths(markdown_line):
    """从 Markdown 表格行中提取图片路径"""
    pattern = r'!\[.*?\]\((.*?)\)'
    matches = re.findall(pattern, markdown_line)
    return matches


def merge_images_horizontal(image_paths, output_path, spacing=10, base_dir='.'):
    """将多张图片从左到右横向拼接"""
    if not image_paths:
        return False

    images = []
    for img_path in image_paths:
        full_path = os.path.join(base_dir, img_path)
        if not os.path.exists(full_path):
            print(f"  ⚠️  跳过不存在的图片: {img_path}")
            continue
        try:
            img = Image.open(full_path)
            images.append(img)
        except Exception as e:
            print(f"  ❌ 加载失败 {img_path}: {e}")

    if not images:
        return False

    # 计算尺寸（等高拼接）
    max_height = max(img.height for img in images)
    total_width = sum(img.width for img in images) + spacing * (len(images) - 1)

    # 创建画布并拼接
    merged_image = Image.new('RGB', (total_width, max_height), 'white')
    x_offset = 0
    for img in images:
        y_offset = (max_height - img.height) // 2
        merged_image.paste(img, (x_offset, y_offset))
        x_offset += img.width + spacing

    # 保存
    merged_image.save(output_path)
    return True


def find_table_rows(markdown_content):
    """
    查找 Markdown 文件中所有包含图片的表格行

    返回: [(行号, 行内容, 上一行标题), ...]
    """
    lines = markdown_content.split('\n')
    table_rows = []
    last_heading = "未命名"

    for i, line in enumerate(lines, 1):
        # 记录最近的标题作为上下文
        if line.strip().startswith('#'):
            last_heading = line.strip().lstrip('#').strip()

        # 判断是否为包含图片的表格行（不是分隔行）
        if '|' in line and '![' in line and not line.strip().startswith('|:') and not line.strip().startswith('| :'):
            table_rows.append((i, line, last_heading))

    return table_rows


def sanitize_filename(text):
    """将标题文本转换为安全的文件名"""
    # 移除或替换特殊字符
    text = re.sub(r'[\\/*?:"<>|]', '', text)
    text = text.replace(' ', '-')
    return text[:50]  # 限制长度


def process_markdown_file(md_file_path):
    """处理整个 Markdown 文件，批量生成拼接图片"""
    md_path = Path(md_file_path)

    if not md_path.exists():
        print(f"❌ 文件不存在: {md_file_path}")
        return

    print("=" * 70)
    print(f"📄 正在处理: {md_path.name}")
    print("=" * 70)
    print()

    # 读取文件
    with open(md_path, 'r', encoding='utf-8') as f:
        content = f.read()

    # 查找所有图片表格行
    table_rows = find_table_rows(content)

    if not table_rows:
        print("⚠️  未找到包含图片的表格行")
        return

    print(f"🔍 找到 {len(table_rows)} 个图片表格行\n")

    # 创建输出目录
    output_dir = md_path.parent / 'merged-images'
    output_dir.mkdir(exist_ok=True)

    # 逐个处理
    success_count = 0
    for idx, (line_num, line_content, heading) in enumerate(table_rows, 1):
        print(f"[{idx}/{len(table_rows)}] 处理第 {line_num} 行（{heading}）")

        # 提取图片路径
        image_paths = extract_image_paths(line_content)
        print(f"  📸 图片数量: {len(image_paths)}")

        if not image_paths:
            print("  ⚠️  未找到图片，跳过\n")
            continue

        # 生成输出文件名
        safe_heading = sanitize_filename(heading)
        output_filename = f"merged-{idx:02d}-{safe_heading}.png"
        output_path = output_dir / output_filename

        # 拼接图片
        if merge_images_horizontal(image_paths, str(output_path), spacing=10, base_dir=str(md_path.parent)):
            print(f"  ✅ 已保存: {output_filename}")
            success_count += 1
        else:
            print(f"  ❌ 拼接失败")

        print()

    print("=" * 70)
    print(f"✅ 完成！成功生成 {success_count}/{len(table_rows)} 张拼接图片")
    print(f"📁 输出目录: {output_dir}")
    print("=" * 70)


if __name__ == '__main__':
    if len(sys.argv) > 1:
        # 从命令行参数获取文件路径
        md_file = sys.argv[1]
    else:
        # 默认处理当前目录下的 md 文件
        current_dir = Path(__file__).parent
        md_file = current_dir / '宇视运动小程序功能模块梳理.md'

    process_markdown_file(md_file)
